const SpecialGroup = require("./SpecialGroup").SpecialGroup;
const CommonAxerrHG = require("../../tool/CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;
const setCookieParser = require("set-cookie-parser");
const util = require("util");
const process = require("process");

class WpsCom {
  /**
   * 
   * @param {String} wps_sid 
   * @param {string} csrf
   */
  constructor(wps_sid, csrf = "") {
    this.wps_sid = wps_sid;
    this.csrf_token = csrf || WpsCom.CreateCsrfToken();
    this.__appendCookies = [{
      name: "singleSignStart",
      value: `${Date.now()}`
    }, {
      name: "wpsqing_autoLoginV1",
      value: "1"
    }, {
      name: "wps_region",
      value: 'apse1'
    }, {
      name: "submenuOpen",
      value: "false"
    }];

    this.GetSpecialGroupPromise = this.ONLY_ONCE_getSpecialGroupInfo();
    var wps = this;
    var _doitAfterNew = (function init() {
      //在wps.com 并不需要做
      wps.axios.get('https://drive.wps.com/?show=all', {
        headers: {
          cookie: wps.cookies_as_header
        }
      }).then(axresp => {
        debugger
        if (axresp.headers
          && axresp.headers["set-cookie"]) {
          let parsed = setCookieParser.parse(axresp.headers["set-cookie"]);
          if (parsed && parsed.length) {
            let hasValue = parsed.filter(e => !!e.value);
            hasValue.forEach(e => {
              wps.__appendCookies.push({
                name: e.name,
                value: e.value
              })
            })
          }
          // debugger
        }
      }).catch(axerr => {
        //DO NOTHING?
      })
    });

  }

  get cookies_as_header() {
    return `wps_sid=${
      this.wps_sid
      }; csrf=${
      this.csrf_token
      }; ${this.__appendCookies.map(e => `${e.name}=${e.value}`).join("; ")}`
  }

  get iphost(){
    if(process.env.WPSCOMIP){
      return process.env.WPSCOMIP
    }else{
      return "drive.wps.com"
    }
  }


  /**
  * @api private
  * @returns {Promise<{ok:Boolean,msg:String,data:{special_group:SpecialGroup}}>}
  */
  ONLY_ONCE_getSpecialGroupInfo() {
    return new Promise(resolve => {
      this.axios.get(`https://${this.iphost}/api/v3/groups/special`, {
        headers: {
          host:"drive.wps.com",
          cookie: this.cookies_as_header,
          referer: "https://drive.wps.com/"
        }
      }).then(axresp => {
        // debugger
        if (axresp.data
          && axresp.data.type == "special"
          && axresp.data.id
          && axresp.data.name) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              // id: axresp.data.id,
              // name: axresp.data.name,
              special_group: new SpecialGroup(this,
                axresp.data.id, axresp.data.name)
            }
          })
        }

        throw axresp.data;
      }).catch(axerr => {
        CommonAxerrHG(resolve)(axerr);
      })
    })
  }

  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{
   * id:Number,
   * name:String,
   * total:Number,
   * used:Number
   * }}>}
   */
  getSpaces() {
    return new Promise(resolve => {
      this.axios.get(`https://${this.iphost}/api/v3/spaces`, {
        headers: {
          host:"drive.wps.com",
          cookie: this.cookies_as_header,
          referer: "https://drive.wps.com/?zeus=1"
        }
      }).then(axresp => {
        if (axresp.data.total
          && axresp.data.total
          && axresp.data.name
          && axresp.data.id) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              id: axresp.data.id,
              name: axresp.data.name,
              total: axresp.data.total,
              used: axresp.data.used
            }
          })
        }
        // debugger
        throw axresp.d
      }).catch(axerr => {
        CommonAxerrHG(resolve)(axerr);
      })
    })
  }

  /**
   * @description 这个file_id既适用于文件也可以用于文件夹;不需要group的参数欸...
   * @returns {Promise<{ok:Boolean,msg:String,data:{
    * path:Array<{
      * fileid:Number,
      * fname:String
      * }>
      * }}>}
      * @param {Number} file_id 
      */
  getPathTo(file_id) {
    return new Promise(resolve => {
      this.axios.get(`https://${this.iphost}/api/files/${
        file_id
        }/path`, {
        headers: {
          host:"drive.wps.com",
          cookie: this.cookies_as_header
        }
      }).then(axresp => {
        if(axresp.data
          &&util.isArray(axresp.data.path)){
            return resolve({
              ok:true,
              msg:"ok",
              data:{
                path:axresp.data.path
              }
            })
        }
        throw axresp.data
      }).catch(axerr => {
        CommonAxerrHG(resolve)(axerr);
      })
    })
  }




}

WpsCom.prototype.axios = require("./wps_axios");
/**
 * 
 * @returns {string} 得到一个客户端生成的CSRF TOKEN
 */
WpsCom.CreateCsrfToken = function () {
  var a = ""
    , b = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
    , c = b.length;
  for (i = 0; i < 32; i++)
    a += b.charAt(Math.floor(Math.random() * c));
  return a;
}


module.exports = WpsCom;